package com.m3839.sdk.ym.widget.toast

import android.R
import android.app.Activity
import android.os.Handler
import android.os.Looper
import android.support.annotation.LayoutRes
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout

/**
 * Description:HykbToast
 *
 * @author 陈宝阳
 * @create 2020/4/27 10: 51
 */
class HykbToast private constructor(private val mActivity: Activity) {

    private val mInflater: LayoutInflater = LayoutInflater.from(mActivity)
    private var mRootView: ViewGroup? = null
    private var mContent: View? = null
    private var mGravity = Gravity.CENTER

    private fun initRootView() {
        mRootView =
            mActivity.window.decorView.findViewById(R.id.content)
    }

    fun setContentView(contentView: View?): HykbToast {
        mContent = contentView
        return this
    }

    fun setContentView(@LayoutRes contentViewId: Int): HykbToast {
        mContent = mInflater.inflate(contentViewId, mRootView, false)
        return this
    }

    fun gravity(gravity: Int): HykbToast {
        mGravity = gravity
        return this
    }

    private fun showContent() {
        if (mContent != null) {
            if (mContent!!.parent == null) {
                mContent!!.isClickable = false
                if (mGravity != -1) {
                    val params =
                        mContent!!.layoutParams as FrameLayout.LayoutParams
                    params.gravity = mGravity
                    mContent!!.layoutParams = params
                }
                mRootView!!.addView(mContent)
            }
        }
    }

    private fun hideContent() {
        HANDLER.postDelayed({ mRootView!!.removeView(mContent) }, 2000)
    }

    fun show() {
        showContent()
        hideContent()
    }

    companion object {
        private val HANDLER = Handler(Looper.getMainLooper())
        fun with(activity: Activity): HykbToast {
            return HykbToast(activity)
        }
    }

    init {
        initRootView()
    }
}